# 练习作用域之间的转换
import time
b = 2


def foo():   # *** 全局变量 ***
    global b
    b = 4
    print(b)


def make_averager():  # 自由变量
    total = 0
    count = 0
    def averager(value):
        nonlocal total, count
        total += value
        count += 1
        return total / count
    return averager


a = 3
c = []


def foo2():  # 局部变量测试
    a = 4
    c.append(3)
    return None


# 默写一个装饰器, 用来输出函数的执行时间.
def clock_it(func):
    def wrapper(*args, **kwargs):
        stat_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__}运行时间为:{format(end_time-stat_time,'.2f')}s")
        return result
    return wrapper


@clock_it
def my_calculation():
    my_num = 0
    n = 0
    while True:
        if n == 1000000:
            break
        my_num += 1
        n += 1


# 使用装饰器来为斐波那契函数添加缓存
def cache_deco(func):
    cache = {}

    def wrapper(n):
        if n in cache:
            return cache[n]
        result = func(n)
        cache[n] = result
        return result
    return wrapper


@cache_deco
def my_fibo(n):
    if n < 2:
        return n
    return my_fibo(n - 1) + my_fibo(n - 2)


if __name__ == "__main__":
    foo()
    my_avg = make_averager()
    print(my_avg(4))
    foo2()
    print(a)
    print(c)
    my_calculation()
    print(my_fibo(10))
    print(my_fibo(10))
